import { defineStore } from 'pinia'

type Todos = {
  id: number
  name: string
  done: boolean
}[]

const useTodosStore = defineStore('todos', {
  state: () => ({
    list: JSON.parse(localStorage.getItem('todos') || '[]') as Todos,
    // 所有的导航
    navs: ['All', 'Active', 'Completed'],
    // 激活All
    active: 'All',
  }),
  actions: {
    delTodo(id: number) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    changeTodo(id: number) {
      const todo = this.list.find((item) => item.id === id)!
      todo.done = !todo.done
    },
    addTodo(name: string) {
      this.list.unshift({
        id: Date.now(),
        name,
        done: false,
      })
    },
    checkAll(value: boolean) {
      this.list.forEach((item) => (item.done = value))
    },
    clearTodo() {
      this.list = this.list.filter((item) => !item.done)
    },
    changeActive(nav: string) {
      this.active = nav
    },
  },
  getters: {
    isCheckAll(): boolean {
      return this.list.every((item) => item.done)
    },
    leftCount(): number {
      return this.list.filter((item) => !item.done).length
    },
    showClear(): boolean {
      // 如果list中有一个或者多个任务是完成的，就显示
      return this.list.some((item) => item.done)
    },
    showList(): Todos {
      if (this.active === 'Active') {
        return this.list.filter((item) => !item.done)
      } else if (this.active === 'Completed') {
        return this.list.filter((item) => item.done)
      } else {
        return this.list
      }
    },
  },
})

export default useTodosStore
